package com.app.business.service;

import com.app.business.model.ZsProjectUser;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.permission.model.UserInfo;
import com.app.system.permission.service.UserInfoService;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.exception.Precondition;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户征收项目业务层
 * Created by lsh on 2019/2/15.
 *
 * @author lsh
 */
@Service
@SuppressWarnings("ALL")
public class ZsProjectUserService extends JpaBaseDao<ZsProjectUser, Integer> {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private ZsProjectService zsProjectService;
    @Autowired
    private ZsProjectUserService zsProjectUserService;


    /**
     * 根据userInfoId获取List<zsProjectId>
     *
     * @param zsProjectUserId
     * @return
     */
    public List<Integer> getZsProjectIdByUserInfoId(Integer userInfoId) {
        String sql = "select p.zs_project_id from zs_project_user p where p.user_info_id =:userInfoId";
        return this.entityManager.createNativeQuery(sql)
                .setParameter("userInfoId", userInfoId)
                .getResultList();
    }


    /**
     * 通过userInfoId批量删除
     *
     * @param userInfoId
     * @return
     */
    @Transactional
    public int deleteByUserInfoId(Integer userInfoId) {
        StringBuffer hql = new StringBuffer("delete from zs_project_user where user_info_id  =:user_info_id");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("user_info_id", userInfoId);
        return this.executeSql(hql.toString(), map);
    }

    /**
     * 用户分配征收项目保存
     *
     * @param request
     */
    @Transactional
    public void formSave(HttpServletRequest request) {
        int userInfoId = ParamUtils.getInt(request, "userInfoId", 0);
        UserInfo userInfo = this.userInfoService.findOne(userInfoId);
        Precondition.checkSqdsArguement(userInfo != null, "用户信息不存在！");
        int[] zsProjectIdArray = ParamUtils.getIntParameters(request, "zsProjectIds");

        //待生成的ZsProjectUser
        List<ZsProjectUser> zsProjectUserForNewList = Lists.newLinkedList();
        ZsProjectUser zsProjectUser = null;
        for (Integer zsProjectId : zsProjectIdArray) {
            zsProjectUser = null;
            zsProjectUser = new ZsProjectUser();
            zsProjectUser.setUserInfoId(userInfoId);
            zsProjectUser.setZsProjectId(zsProjectId);
            zsProjectUserForNewList.add(zsProjectUser);
        }


        this.deleteByUserInfoId(userInfo.getId());
        this.batchSave(zsProjectUserForNewList);
    }

}
